package cn.jtfadmin.base.shiro.filters;

import cn.jtfadmin.base.lang.common.domain.dto.ResultDTO;
import cn.jtfadmin.base.lang.common.utils.JsonUtils;
import cn.jtfadmin.base.shiro.config.ShiroCustomerFilter;
import cn.jtfadmin.base.shiro.config.ShiroWebFilterConfig;
import cn.jtfadmin.base.shiro.statuscode.NoAuthorityStatusCodeConfig;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * shiro userFilter 复写返回值为json
 *
 * @author jtf
 * @see ShiroCustomerFilter
 * @see ShiroWebFilterConfig
 * @since 0.0.1
 */
@Component
public class ShiroRoleFilter implements ShiroCustomerFilter {

    public final static String NAME = DefaultFilter.roles.name();


    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public Filter getFilter() {
        return new RolesAuthorizationFilter() {
            // 未认证跳转登录
            protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.getOutputStream().write(JsonUtils.toJsonStr(ResultDTO.error(NoAuthorityStatusCodeConfig.NO_AUTHORITY_CODE, "登录失效请重新登录"))
                        .getBytes(StandardCharsets.UTF_8));
            }
        };
    }


}


